const { DataTypes, Model, Deferrable, TINYINT, INTEGER, Op } = require("sequelize");
const sequelize = require("../../db/sequelize");
/**
 * 商品分类模型
 */
class Category extends Model {
    /**
     * 异步子查父分类
     */
    async getParent() {
        //为0是没有父分类，返回自身的json格式
        if (this.category_id == 0) {
            return this.toJSON()
        }
        let parent = await Category.findOne({
            where: {
                id: this.category_id
            }
        })
        let json = this.toJSON()
        json["parent"] = await parent.getParent()
        return json
    }
    /**
     * 异步子查父分类
     * @param {*} id 
     */
    static async getParent(id) {
        let json = await Category.findOne({
            where: {
                id: id
            }
        })
        if (json == null) {
            return []
        }
        return json.getParent()
    }
    static async getCategoryAll() {
        let json = []
        await this.findAll({
            where: {
                category_id: 0
            }
        }).then(async row => {
            row.forEach(async (value) => {
                json.push(this.getChild(value.toJSON()));
            })
            json = await Promise.all(json)
        })
        return json
    }
    /**
     * 异步父查子
     * @param {} object 
     * @returns 
     */
    static async getChild(object) {
        if (!object.child) {
            object["child"] = []
        }
        let category = await Category.findAll({
            where: {
                "category_id": object.id
            }
        })
        if (category.length == 0) {
            delete object["child"]
            return object
        }
        for (let i = 0; i < category.length; i++) {
            let js = category[i].toJSON()
            js["child"] = []
            object["child"].push(Category.getChild(js))
        }
        object["child"] = await Promise.all(object["child"])
        return object
    }
}
Category.init({
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    name: {
        type: DataTypes.STRING
    },
    status: {
        type: TINYINT
    },
    category_id: {
        type: INTEGER
    },
    order: {
        type: INTEGER
    }
}, {
    sequelize,
    modelName: "Category",
    tableName: "category",
    createdAt:"create_time",
    updatedAt:"update_time"
})
module.exports = Category